package v2ray

import (
	"context"
	"gitee.com/Luna-CY/hui-hui/internal/interface/application"
	"gitee.com/Luna-CY/hui-hui/internal/logger"
	"gitee.com/Luna-CY/hui-hui/internal/runtime"
	"gitee.com/Luna-CY/hui-hui/internal/util/syscall"
	"github.com/hashicorp/go-version"
	"os/exec"
	"path/filepath"
	"strings"
)

func (cls *V2ray) CheckLocationState(ctx context.Context) error {
	logger.GetLogger().Sugar().Info("检测V2ray服务本地状态")
	command, err := exec.LookPath(filepath.Join(rootPath, "v2ray"))
	if nil == err {
		output, err := syscall.ExecuteCommandGetOutputIgnoreQuitCode(ctx, command, "version")
		if nil != err {
			return err
		}

		// 解析版本号
		if 0 != len(output) {
			var tokens = strings.Split(output[0], " ")
			if 0 != len(tokens) {
				min, err := version.NewVersion(runtime.V2rayMinimumVersion)
				if nil != err {
					return err
				}

				tv, err := version.NewVersion(tokens[1])
				if nil != err {
					return err
				}

				// 如果大于或等于最小版本号则返回
				if tv.GreaterThanOrEqual(min) {
					cls.UpdateState(application.Installed, 0, "")

					return nil
				}

				cls.UpdateState(application.VersionNotEffect, 0, "")

				return nil
			}
		}
	}

	cls.UpdateState(application.NotInstall, 0, "")

	return nil
}
